import axios from 'axios'
import { message } from 'antd'
import { showLoading, hideLoading } from './loading'
import storage from './storage'

const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 8000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true
})
console.log(import.meta.env)

// 请求拦截器
instance.interceptors.request.use(
  config => {
    showLoading()
    const token = storage.getAccessToken()
    if (token) {
      config.headers.Authorization = token
    }
    config.baseURL =
      import.meta.env.VITE_MOCK === 'true' ? import.meta.env.VITE_MOCK_API : import.meta.env.VITE_BASE_API
    return {
      ...config
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    hideLoading()
    const { data } = response
    if (data.code === 50001) {
      message.error(data.msg)
      storage.removeAccessToken()
      location.href = '/login'
    } else if (data.code !== 0) {
      message.error(data.msg)
      return Promise.reject(data)
    }
    return data.data
  },
  error => {
    hideLoading()
    message.error(error.message)
    return Promise.reject(error.message)
  }
)

export default {
  get<T>(url: string, params?: object): Promise<T> {
    return instance.get(url, { params })
  },
  post<T>(url: string, params: object): Promise<T> {
    return instance.post(url, params)
  }
}
